package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/20 14:55
 * @Description:登录
 */
@RestController
@RequestMapping("/login")
public class LoginController {

	@Autowired
	JedisPool jedisPool;

	@Reference
	MemberService memberService;
	
	/**
	 *  @描述：登录
	 */
	@RequestMapping("/check")
	public Result check(@RequestBody Map map, HttpServletResponse response) {
		String telephone = String.valueOf(map.get("telephone"));
		// 1.验证验证码
		// 1-1 前端的验证码
		String validateCode = String.valueOf(map.get("validateCode"));
		// 1-2 redis验证码
		String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
		if(StringUtils.isEmpty(codeInRedis) || !codeInRedis.equals(validateCode)){
		//	 验证码错误
			return new Result(false, MessageConstant.VALIDATECODE_ERROR);
		}
		// 如果不是用户，自动完成注册
		Member member=memberService.findByTelephone(telephone);
		if(ObjectUtils.isEmpty(member)){
			member =new Member().builder().phoneNumber(telephone).regTime(new Date()).build();
			memberService.add(member);

		}
		// 如果使用户，完成登录
		// 将用户的手机号存入Cookie，将用户的信息放入redis，每一次请求过来的时候，从cookie获取用户的手机号，再去Redis查询用户信息
		Cookie cookie = new Cookie("telephone",telephone);
		cookie.setMaxAge(60*60*24*30);
		cookie.setPath("/");
		response.addCookie(cookie);

		return new Result(true, MessageConstant.LOGIN_SUCCESS);
	}
}
